#import "DDTextField.h"
#import "NSString+category.h"
CGFloat const LEFTVIEW_HEIGHT = 30;
CGFloat const TEXTFILDHEIGHT = 44;
@interface DDTextField()<UITextFieldDelegate>
@property (nonatomic, strong) UIView *line;
@property (nonatomic, strong) DDButton *verifyBtn;
@property (nonatomic, strong) CCTime *timer;
@end
@implementation DDTextField
- (instancetype)init
{
    self = [super init];
    if (self)
    {
        [self setup];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setup];
    }
    return self;
}
- (instancetype)initWithPlaceholder:(NSString *)placeholder
{
    self = [super init];
    if (self)
    {
        self.placeholder = placeholder;
        [self setup];
    }
    return self;
}
- (CCTime *)timer
{
    if (!_timer)
    {
        _timer = [[CCTime alloc] init];
    }
    return _timer;
}
- (DDButton *)rightBtn
{
    if (!_rightBtn)
    {
        _rightBtn = [[DDButton alloc] initWithFrame:CGRectMake(0, 0, LEFTVIEW_HEIGHT, LEFTVIEW_HEIGHT)];
        _rightBtn.imageName = @"secure";
        [_rightBtn addTarget:self action:@selector(actionShowSecureBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_rightBtn];
        _rightBtn.c_right.c_equal(self).with.coffset(-GAP / 2.0);
        _rightBtn.c_centerY.c_equal(self);
        _rightBtn.c_size.c_equal(self.rightBtn.bounds.size);
    }
    return _rightBtn;
}
- (DDButton *)verifyBtn
{
    if (!_verifyBtn)
    {
        _verifyBtn = [[DDButton alloc]init];
        _verifyBtn.backgroundColor = [DDHelper help].color;
        _verifyBtn.title = @"获取验证码";
        [_verifyBtn setValue:FONT(UIFontWeightLight, 13) forKeyPath:@"_label.font"];
        [_verifyBtn addTarget:self action:@selector(dd_actionForYanZhenBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_verifyBtn];
        _verifyBtn.c_right.c_equal(self);
        _verifyBtn.c_top.c_equal(self);
        _verifyBtn.c_bottom.c_equal(self);
        _verifyBtn.c_width.c_equal(100);
    }
    return _verifyBtn;
}
- (UIView *)line
{
    if (!_line)
    {
        _line = [[UIView alloc]init];
        _line.backgroundColor = [UIColor lightGrayColor];
        _line.bounds = CGRectMake(0, 0, 1.0, 25);
        [self addSubview:_line];
        _line.c_left.c_equal(self).with.coffset(LEFTVIEW_HEIGHT + GAP);
        _line.c_centerY.c_equal(self);
        _line.c_size.c_equal(self.line.bounds.size);
    }
    return _line;
}
- (void)setup
{
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = GAP / 2.0;
    self.layer.borderColor = [UIColor clearColor].CGColor;
    self.layer.borderWidth = 0.5;
    self.layer.masksToBounds = YES;
    self.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.type = JTWTextFieldTypeDefault;
    self.delegate = self;
}
- (void)actionShowSecureBtn:(DDButton *)sender
{
    sender.selected = !sender.selected;
    switch (_type)
    {
        case JTWTextFieldTypeAccountList:
        case JTWTextFieldTypeIDCart:
            sender.imageName = (sender.selected)?@"up":@"down";
            if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(dd_actionForXiaLa:)])
            {
                [self.customDelegate dd_actionForXiaLa:sender.selected];
            }
            break;
        case JTWTextFieldTypePassword:
            sender.imageName = (sender.selected)?@"secure":@"un_secure";
            self.secureTextEntry = !sender.selected;
            break;
        default:
            break;
    }
}
- (void)dd_actionForYanZhenBtn:(DDButton *)sender
{
    BOOL clicked = NO;
    if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(dd_actionForVerifyCode)])
    {
        clicked = [self.customDelegate dd_actionForVerifyCode];
        sender.selected = clicked;
        sender.backgroundColor = (sender.selected)?TEXT_GRAY_COLOR:[DDHelper help].color;
        if (clicked)
        {
            sender.userInteractionEnabled = NO;
            [self.timer countDown:60 time:^(NSString *time) {
                sender.title = [NSString stringWithFormat:@"已获取(%@s)", time];
            } complete:^{
                sender.title = @"获取验证码";
                sender.selected = NO;
                sender.userInteractionEnabled = YES;
                sender.backgroundColor = (sender.selected)?TEXT_GRAY_COLOR:[DDHelper help].color;
            }];
        }
    }
}
- (void)dd_stopTimer
{
    if (_timer)
    {
        [_timer cancel];
        _verifyBtn.selected = NO;
        _verifyBtn.userInteractionEnabled = YES;
        _verifyBtn.backgroundColor = [DDHelper help].color;
    }
}
- (void)setType:(JTWTextFieldType)type
{
    if (_type != type)
    {
        _type = type;
        self.keyboardType = (_type == JTWTextFieldTypeDefault)?UIKeyboardTypeDefault:UIKeyboardTypeASCIICapable;
        switch (_type)
        {
            case JTWTextFieldTypeDefault:
                self.line.hidden = YES;
                break;
            case JTWTextFieldTypeAccountList:
                self.rightBtn.imageName = @"down";
                [self dd_setupLeftView:@"userInput"];
                break;
            case JTWTextFieldTypeAccountNormal:
                [self dd_setupLeftView:@"userInput"];
                self.rightBtn.hidden = YES;
                break;
            case JTWTextFieldTypePassword:
                self.rightBtn.imageName = @"un_secure";
                self.secureTextEntry = YES;
                [self dd_setupLeftView:@"pwdInput"];
                break;
            case JTWTextFieldTypeVerify:
                self.verifyBtn.hidden = NO;
            self.keyboardType = UIKeyboardTypeNumberPad;
                [self dd_setupLeftView:@"phone"];
                break;
            case JTWTextFieldTypePhoneNumber:
            self.keyboardType = UIKeyboardTypeNumberPad;
                [self setupLeftText:@"+86"];
                break;
            case JTWTextFieldTypeIDCart:
                self.rightBtn.imageName = @"down";
                [self dd_setupLeftView:@"userInput"];
                break;
            default:
                break;
        }
    }
}

- (void)dd_setupRightView:(NSString *)imageName
{
    DDImageView *imageView = [[DDImageView alloc]init];
    imageView.imageName = imageName;
    imageView.bounds = CGRectMake(0, 0, LEFTVIEW_HEIGHT, LEFTVIEW_HEIGHT);
    self.rightView = imageView;
    self.rightViewMode = UITextFieldViewModeAlways;
}
- (void)dd_setupLeftView:(NSString *)imageName
{
    DDImageView *imageView = [[DDImageView alloc]init];
    imageView.imageName = imageName;
    imageView.bounds = CGRectMake(0, 0, LEFTVIEW_HEIGHT, LEFTVIEW_HEIGHT);
    self.leftView = imageView;
    self.leftViewMode = UITextFieldViewModeAlways;
    self.line.hidden = NO;
}
- (void)setupLeftText:(NSString *)text
{
    UILabel *label = [[UILabel alloc]init];
    label.font = [UIFont systemFontOfSize:13 weight:UIFontWeightLight];
    label.text = text;
    label.bounds = CGRectMake(0, 0, LEFTVIEW_HEIGHT, LEFTVIEW_HEIGHT);
    self.leftView = label;
    self.leftViewMode = UITextFieldViewModeAlways;
    self.line.hidden = NO;
}
- (void)dd_setupRightBtnTitle:(NSString *)title
{
}
- (CGRect)rightViewRectForBounds:(CGRect)bounds
{
    CGRect  iconRect = [super rightViewRectForBounds:bounds];
    return iconRect;
}
- (CGRect)leftViewRectForBounds:(CGRect)bounds
{
    CGRect inset = [super leftViewRectForBounds:bounds];
    inset.origin.x += GAP / 2.0;
    return CGRectMake(5, 5, 30, 30);
    return inset;
}
- (CGRect)clearButtonRectForBounds:(CGRect)bounds
{
    CGRect  iconRect = [super clearButtonRectForBounds:bounds];
    if (_type == JTWTextFieldTypeAccountList)  iconRect.origin.x -= 20;
    else if (_type == JTWTextFieldTypePassword) iconRect.origin.x -= 30;
    else if (_type == JTWTextFieldTypeVerify) iconRect.origin.x -= 100;
    return iconRect;
}
- (CGRect)textRectForBounds:(CGRect)bounds
{
    CGRect inset = [super textRectForBounds:bounds];
    inset.origin.x += GAP;
    if (_type == JTWTextFieldTypeAccountList)  inset.size.width -= 20;
    else if (_type == JTWTextFieldTypePassword) inset.size.width -= 50;
    else if (_type == JTWTextFieldTypeVerify) inset.size.width -= 95;
    return inset;
}
- (CGRect)editingRectForBounds:(CGRect)bounds
{
    CGRect inset = [super editingRectForBounds:bounds];
    inset.origin.x += GAP;
    inset.origin.y += 1;
    if (_type == JTWTextFieldTypeAccountList)  inset.size.width -= 20;
    else if (_type == JTWTextFieldTypePassword) inset.size.width -= 30;
    else if (_type == JTWTextFieldTypeVerify) inset.size.width -= 75;
    return inset;
}
- (void)setupBorderLineWhenBeginEditing
{
    self.layer.borderColor = BLUE_COLOR.CGColor;
}
- (void)setupBorderLineWhenEndEditing
{
    self.layer.borderColor = [UIColor clearColor].CGColor;
}
- (void)dissKongGe:(UITextField *)textField
{
    if ([textField.text containsString:@" "])
    {
        textField.text = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
}
- (UIView *)dd_findSuperView:(UIView *)view
{
    if ([view.superview isKindOfClass:NSClassFromString(@"DDLoginInput")])
    {
        return view.superview;
    }
    else
        return [self dd_findSuperView:view.superview];
}
#pragma mark UITextFieldDelegate 事件
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    CGFloat maxY =  CGRectGetMaxY([textField convertRect:textField.bounds toView:[[[UIApplication sharedApplication] delegate] window]]);
    UIView *keyBoard = [textField findKeyBoard];
    UIViewController *controller = [self superViewController];
    CGFloat map = SCREEN_HEIGHT - maxY - keyBoard.frame.size.height;
    if (map < 0)
    {
//        [UIView animateWithDuration:0.2 animations:^{
//            dispatch_async(dispatch_get_main_queue(), ^{
//                controller.view.transform = CGAffineTransformMakeTranslation(0, map);
//            });
//        }];
    }
    if (self.type == JTWTextFieldTypeIDCart)
        return NO;
    [self setupBorderLineWhenBeginEditing];
    if (_type == JTWTextFieldTypeAccountList && self.rightBtn.selected)
    {
        [self performSelector:@selector(actionShowSecureBtn:) withObject:self.rightBtn];
    }
    else if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(textFieldShouldBeginEditing:)])
        return [self.customDelegate textFieldShouldBeginEditing:textField];
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self resignFirstResponder];
    if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(textFieldShouldReturn:)])
        return [self.customDelegate textFieldShouldReturn:textField];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *tem = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@""];
    [self dissKongGe:textField];
    if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(textField: shouldChangeCharactersInRange: replacementString:)])
        return [self.customDelegate textField:textField shouldChangeCharactersInRange:range replacementString:string];
    if (![string isEqualToString:tem])
    {
        return NO;
    }
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    UIViewController *controller = [self superViewController];
    [UIView animateWithDuration:0.2 animations:^{
        controller.view.transform = CGAffineTransformIdentity;
    }];
    [self dissKongGe:textField];
    [self setupBorderLineWhenEndEditing];
    if (self.customDelegate && [self.customDelegate respondsToSelector:@selector(textFieldDidEndEditing:)])
        [self.customDelegate textFieldDidEndEditing:textField];
}
@end
